$(document).ready(function(){
	$('table.invoice tfoot tr.addnew td:first button').click( function(e) {
		e.preventDefault();
		
		var departmentField = $('table.invoice tfoot tr.addnew td:eq(1) input:first');
		var descriptionField = $('table.invoice tfoot tr.addnew td:eq(1) input:eq(1)');
		var costField = $('table.invoice tfoot tr.addnew td:last input');
		
		departmentField.siblings('span').remove();
		costField.siblings('span').remove();
		
		if (!departmentField.val().length) {
			$(departmentField).after('<span>Please enter a title for this invoice entry</span>');
		} else if (!costField.val().length) {
			$(costField).after('<span>Please enter a cost for this invoice entry</span>');
		} else {
			var randomnumber = Math.floor(Math.random()*10000);
			
			$('table.invoice tbody').append( '<tr><td><input type="checkbox" checked="checked" name="includeextras[]" value="ext'+randomnumber+'" /></td><td><input type="text" value="'+departmentField.val()+'" name="ext'+randomnumber+'_department" /><input type="text" value="'+descriptionField.val()+'" name="ext'+randomnumber+'_description" /></td><td colspan="5"></td><td>&pound;<input type="text" value="'+costField.val()+'" name="ext'+randomnumber+'_cost" /></td></tr>' );
	
				
			departmentField.val('');
			departmentField.siblings('span').remove();
			descriptionField.val('');
			costField.val('');
			costField.siblings('span').remove();
		}
	});

	$('span.recalculate').click( function (e) {
		$(e).calculateCost();
	});
	
});

$.fn.calculateCost = function () {
	var totalCost = parseFloat(0);
	
	$('table.invoice tbody tr').find('td:last input').each ( function() {
		
		if ( parseFloat($(this).val()) ) totalCost += parseFloat($(this).val());
		
	});
	
	$('span.total').text(totalCost.toString());
}